package com.health.user.service.impl;

import com.health.common.constant.CacheConstants;
import com.health.common.constant.UserConstants;
import com.health.common.core.domain.entity.SysRole;
import com.health.common.core.domain.entity.SysUser;
import com.health.common.exception.ServiceException;
import com.health.common.utils.DateUtils;
import com.health.common.utils.MinIOUtils;
import com.health.common.utils.SecurityUtils;
import com.health.common.utils.StringUtils;
import com.health.system.service.ISysRoleService;
import com.health.system.service.ISysUserService;
import com.health.user.domain.CommonUser;
import com.health.user.domain.UserDetail;
import com.health.user.domain.dto.CaptchaDTO;
import com.health.user.domain.vo.UserDetailVO;
import com.health.user.mapper.CommonUserMapper;
import com.health.user.mapper.UserDetailMapper;
import com.health.user.service.ICommonUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 账号管理Service业务层处理
 *
 * @author zt
 * @date 2025-10-27
 */
@Service
public class CommonUserServiceImpl implements ICommonUserService {
    @Autowired
    private CommonUserMapper commonUserMapper;
    @Autowired
    private UserDetailMapper userDetailMapper;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询账号管理
     *
     * @param userId 账号管理主键
     * @return 账号管理
     */
    @Override
    public CommonUser selectCommonUserByUserId(Long userId) {
        return commonUserMapper.selectCommonUserByUserId(userId);
    }

    /**
     * 查询账号管理列表
     *
     * @param commonUser 账号管理
     * @return 账号管理
     */
    @Override
    public List<CommonUser> selectCommonUserList(CommonUser commonUser) {
        return commonUserMapper.selectCommonUserList(commonUser);
    }

    /**
     * 新增账号管理
     *
     * @param commonUser 账号管理
     * @return 结果
     */
    @Override
    public int insertCommonUser(CommonUser commonUser) throws RuntimeException {
        String username = commonUser.getUserName(), password = commonUser.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException( "用户名不能为空");
        } else if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("用户密码不能为空");
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new RuntimeException("账户长度必须在2到20个字符之间");
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new RuntimeException("密码长度必须在5到20个字符之间");
        } else if (!userService.checkUserNameUnique(sysUser)) {
            throw new RuntimeException("保存用户'" + username + "'失败，注册账号已存在");
        }
        // 设置用户类型为普通用户
        commonUser.setUserType(UserConstants.COMMON_USER);
        commonUser.setPassword(SecurityUtils.encryptPassword(password));
        commonUser.setCreateTime(DateUtils.getNowDate());
        return commonUserMapper.insertCommonUser(commonUser);
    }

    /**
     * 修改账号管理
     *
     * @param commonUser 账号管理
     * @return 结果
     */
    @Override
    public int updateCommonUser(CommonUser commonUser) {
        commonUser.setUpdateTime(DateUtils.getNowDate());
        return commonUserMapper.updateCommonUser(commonUser);
    }

    /**
     * 批量删除账号管理
     *
     * @param userIds 需要删除的账号管理主键
     * @return 结果
     */
    @Override
    public int deleteCommonUserByUserIds(Long[] userIds) {
        return commonUserMapper.deleteCommonUserByUserIds(userIds);
    }

    /**
     * 删除账号管理信息
     *
     * @param userId 账号管理主键
     * @return 结果
     */
    @Override
    public int deleteCommonUserByUserId(Long userId) {
        return commonUserMapper.deleteCommonUserByUserId(userId);
    }

    @Override
    public UserDetailVO selectUserDetailVOByUserId(Long userId) {
        UserDetailVO userDetailVO = new UserDetailVO();
        UserDetail userDetail = userDetailMapper.selectUserDetailByUserId(userId);
        BeanUtils.copyProperties(userDetail, userDetailVO);
        CommonUser commonUser = commonUserMapper.selectCommonUserByUserId(userId);
        BeanUtils.copyProperties(commonUser, userDetailVO);
        userDetailVO.setRoleName(commonUserMapper.selectRoleNameByUserId(userId).get(0));
        return userDetailVO;
    }

    @Autowired
    private MinIOUtils minIOUtils;

    @Override
    public String uploadImg(MultipartFile file, Long userId) {
        String url;
        try {
            url = minIOUtils.uploadFile(file);
            String oldUrl = commonUserMapper.selectAvatarByUserId(userId);
            if (oldUrl != null) minIOUtils.deleteFile(oldUrl);
            commonUserMapper.updateAvatar(url, userId);
        } catch (Exception e) {
            throw new RuntimeException("头像上传失败");
        }
        return url;
    }
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void updatePhone(CaptchaDTO captchaDTO, Long userId) {
        String redisCode = (String) redisTemplate.opsForValue().get(CacheConstants.PHONE_CODE_KEY +captchaDTO.getUuid());
        if (!captchaDTO.getCode().equals(redisCode)) throw new ServiceException("验证码错误");
        commonUserMapper.updatePhone(captchaDTO.getPayload(), userId);
    }

    @Override
    public void updateEmail(CaptchaDTO captchaDTO, Long userId) {
        String redisCode = (String) redisTemplate.opsForValue().get(CacheConstants.EMAIL_CODE_KEY +captchaDTO.getUuid());
        if (!captchaDTO.getCode().equals(redisCode)) throw new ServiceException("验证码错误");
        commonUserMapper.updateEmail(captchaDTO.getPayload(), userId);
    }

    @Override
    @Transactional
    public void updateDetail(UserDetailVO userDetailVO) {
        CommonUser commonUser = new CommonUser();
        commonUser.setUserId(userDetailVO.getUserId());
        commonUser.setNickName(userDetailVO.getNickName());
        commonUser.setSex(userDetailVO.getSex());
        UserDetail userDetail = new UserDetail();
        BeanUtils.copyProperties(userDetailVO, userDetail);
        userDetailMapper.updateUserDetail(userDetail);
        commonUserMapper.updateCommonUser(commonUser);
    }
}
